import {BasePageData} from "../common/core/BasePage";
import {DataLoader, field} from "../../modules/coreModule/data/DataLoader";
import {Task,TaskStatus, TaskType} from "../../modules/taskModule/data/Task";
import {page, pageFunc} from "../common/PageBuilder";
import {ItemDetailPage} from "../common/pages/ItemDetailPage";
import {AuthPage, UserPage} from "../common/partPages/UserPage";
import {PK} from "../../modules/coreModule/data/BaseData";
import {userMgr, waitForLogin} from "../../modules/userModule/managers/UserManager";
import {waitForDataLoad} from "../../modules/coreModule/managers/DataManager";
import {TaskInterface} from "../../modules/taskModule/TaskCommon";
import {ParticInfo, ParticRecord, ParticRecordStatus} from "../../modules/taskModule/data/ParticRecord";
import {CollectRecord, CollectRecordStatus} from "../../modules/taskModule/data/CollectRecord";
import {alertMgr, handleError, IconType} from "../../modules/coreModule/managers/AlertManager";
import {pageMgr} from "../../modules/coreModule/managers/PageManager";
import {ReportPage} from "../report/ReportPage";
import {TemplateIds} from "../../modules/messageModule/MessageCommon";
import {PaymentPage} from "../payment/PaymentPage";
import {RoleType} from "../../modules/userModule/data/Role";
import {blockLoading, showLoading} from "../../modules/coreModule/managers/LoadingManager";
import {CoreLoading} from "../../modules/coreModule/CoreCommon";
import {UserDetailPage} from "../userDetail/UserDetailPage";
import {KidsSignUpPage} from "../kidsSignUp/KidsSignUpPage";
import {DefaultShareImage, ShareAppPage, ShareTimelinePage} from "../common/partPages/SharePage";
import {StringUtils} from "../../utils/StringUtils";

class Data extends BasePageData {

	@field(Task)
	item: Task;

	// TODO: 注意，ParticRecord添加了count的字段
	// 将所有的ParticRecord的count字段相加，才是真正参与的人数
	@field([ParticRecord])
	particRecords: ParticRecord[];
	@field([CollectRecord])
	collectRecords: CollectRecord[];
	@field(Boolean)
	isCollect: boolean
	@field(Boolean)
	isPartic: boolean
	@field(Boolean)
	isSelf: boolean
	@field([String])
	typeName: string[]=["成长训练营", "场地", "日常兼职", "军事训练"]
	@field(Boolean)
	showPopup: boolean
}

class Param {
	id: PK
}

@page("recruitDetail", "活动详情")
export class RecruitDetailPage extends ItemDetailPage<Data, Task, Param> {

	public data = new Data();

	/**
	 * 部分页
	 */
	public userPage: AuthPage = new AuthPage(true, false, false);
	public shareAppPage = new ShareAppPage(RecruitDetailPage);
	public shareTimelinePage = new ShareTimelinePage();

	/**
	 * OnLoad回调
	 */
	onLoad(e) {
		super.onLoad(e);

		this.shareTimelinePage.query.id =
		this.shareAppPage.extra.id =
			this.params.id ||= this.getExtra("id");
		userMgr().savedInviteCode = this.getExtra("code");

		console.log("params", this.params, "extra", this.extra)

		this.loadData().then();
	}

	@showLoading(CoreLoading.Mask)
	@blockLoading
	// @waitForLogin
	@waitForDataLoad
	private async loadData() {
		const res = await TaskInterface.GetTask({ taskId: this.params.id });

		// const openid = this.userPage.openid;
		const task = DataLoader.load(Task, res.task);
		const prs: ParticRecord[] = res.particRecords.map(r => DataLoader.load(ParticRecord, r));
		const crs: CollectRecord[] = res.collectRecords.map(r => DataLoader.load(CollectRecord, r));

		const openid = userMgr().openid
		const isSelf = task.userId == openid;
		const isPartic = prs.some(r => r.userId == openid);
		const isCollect = crs.some(r => r.userId == openid);

		await this.setData({
			item: task, isCollect, isPartic, isSelf,
			particRecords: prs, collectRecords: crs
		})

		this.shareAppPage.onShare = () => ({
			title: this.item.title + " 正在报名中",
			imageUrl: this.item.images[0] || DefaultShareImage,
		});
		this.shareTimelinePage.onShare = () => ({
			title: this.item.title + " 正在报名中",
			imageUrl: this.item.images[0],
		});
	}

	/**
	 * 收藏
	 */
	@pageFunc
	@showLoading(CoreLoading.Mask)
	@blockLoading
	public async collect() {
		await TaskInterface.CollectTask({
			taskId: this.item._id,
			collect: !this.data.isCollect
		})
		await this.setData({
			isCollect: !this.data.isCollect
		})
		const title = this.data.isCollect ? "收藏成功" : "已取消";
		const icon = this.data.isCollect ? "success" : "none";
		await alertMgr().showToast(title, icon);
	}

	/**
	 * 报名
	 */
	@pageFunc
	@handleError
	public async partic() {
		await this.userPage.checkIdentAuth(true);

		if (!this.data.isPartic)
			if (!this.data.item.isCamp) {
				this.ensureRole();
				wx.requestSubscribeMessage({
					tmplIds: [TemplateIds["需求通知"]],
					success: this.doPartic.bind(this)
				})
			} else await pageMgr().push(KidsSignUpPage, {id: this.params.id});
		else await this.doPartic();
	}
	@showLoading(CoreLoading.Mask)
	@blockLoading
	@handleError
	private async doPartic() {
		await TaskInterface.ParticTask({
			taskId: this.item._id,
			partic: !this.data.isPartic,
		})
		await this.setData({
			showPopup: false,
			isPartic: !this.data.isPartic
		})
		const title = this.data.isPartic ? "报名成功" : "取消成功";
		const icon = this.data.isPartic ? "success" : "none";
		await alertMgr().showToast(title, icon);
	}

	/**
	 * 任务所需的角色
	 */
	private ensureRole() {
		switch (this.item.type) {
			case TaskType.Military: // 军训
				this.userPage.ensureRole(RoleType.Instructor, "请先完成教官资质认证！");
				this.ensureInstructorLevel();
				break;
			case TaskType.PartTime: // 兼职
			case TaskType.Reward: // 悬赏
			case TaskType.Camp: // 训练营
				break;
		}
	}

	/**
	 * 保证教官等级
	 */
	private ensureInstructorLevel() {
		const level = this.userPage.certification?.level?.level;
		if (level < this.item.level) throw "教官等级不满足要求！"
	}

	/**
	 * 支付尾款
	 */
	@pageFunc
	public async pay() {
		let tradeId, contractId;
		if (this.item.secondTradeId)
			tradeId = this.item.secondTradeId;
		else {
			tradeId = this.item.firstTradeId;
			contractId = this.item.contractId;
		}
		await pageMgr().change(PaymentPage, <any>{
			tradeId, contractId,
			onSuccess: () =>
				pageMgr().change(RecruitDetailPage, { id: this.item._id })
		})
	}

	/**
	 * 取消
	 */
	@pageFunc
	public async cancel() {
		const res = await alertMgr().showAlert(
			"真的要取消需求吗？如果需求已经开始，将无法退还押金",
			true
		)
		if (res.confirm) await this.doCancel();
	}
	@showLoading(CoreLoading.Mask)
	@blockLoading
	private async doCancel() {
		await TaskInterface.CancelTask({
			taskId: this.item._id
		})
		await alertMgr().showToast("取消成功", "none");
		this.back();
	}

	@pageFunc
	public async removePartic(e) {
		console.log("removePartic", e.target.dataset)
		const userId = e.target.dataset.userid;

		await TaskInterface.RemovePartic({
			taskId: this.item._id, userId
		});

		const particRecords = this.data.particRecords
			.filter(pr => pr.userId != userId);
		await this.setData({particRecords});
	}

	/**
	 * 举报
	 */
	@pageFunc
	public report(){
		pageMgr().push(ReportPage, {taskId: this.item._id}).then();
	}

	/**
	 * 联系
	 */
	@pageFunc
	public contact() {
		if (this.item.phone)
			wx.makePhoneCall({phoneNumber: this.item.phone})
		else
			alertMgr().showAlert("用户未上传电话")
	}

	@pageFunc
	public onClose() {
		this.setData!({ showPopup: false });
	}

	@pageFunc
	public showUserDetail(e) {
		console.log("showUserDetail", e);
		pageMgr().push(UserDetailPage, {id: e.target.dataset.id})
	}
}
